package com.myspring.web.route.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.myspring.web.route.ChannelService;
import com.myspring.web.route.RouteController;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 参考资料：
 *  spring boot 拦截器 或 Spring AOP 方式记录请求日志：https://my.oschina.net/gmd/blog/704372
 *  拦截器解析requestbody：http://stackoverflow.com/questions/10457963/spring-rest-service-retrieving-json-from-request
 */
//@Aspect
//@Component
public class RouteAspectBak implements ApplicationContextAware {
    private ApplicationContext context;

//    @Pointcut("execution(public * com.myspring.web.route..*.loan*(..))")
    public void routeService() {}

    @Before("routeService()")
    public void doBefore(JoinPoint joinPoint) {
//        Class<?> clazz = joinPoint.getSignature().getDeclaringType();

        Object object = context.getBean(joinPoint.getSignature().getDeclaringType());

        if (object instanceof RouteController) {
            RouteController controller = (RouteController) object;
            controller.setChannelService(this.getChannelService());
        }
    }

    private ChannelService getChannelService() {
        ChannelService channelService = null;
        Map<String, String> channelMap = (Map<String, String>) context.getBean("channelMap");

        //获取请求中的bankCode
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

       MyRequestWrapper requestWrapper = new MyRequestWrapper(request);

        Map paramsMap = Maps.newHashMap();
        try {
//            inputStream = request.getInputStream();
//            //json的String转换为Map，map.get("bankCode")具体值
//            System.out.println(inputStream);
//            String requestBody = null;
//            if (inputStream != null) {
//                requestBody = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
//            }
//            System.out.println(requestBody);

            String requestBody = requestWrapper.getBody();
            System.out.println("requestBody:" + requestBody);
            ObjectMapper mapper = new ObjectMapper();
            //请求参数保存到Map
            paramsMap = mapper.readValue(requestBody, HashMap.class);
        }catch (Exception e) {
            e.printStackTrace();
        }

        String channelLiteral = channelMap.get(paramsMap.get("bankCode"));
        if (!StringUtils.isEmpty(channelLiteral)) {
            try {
                Class<?> clazz = Class.forName(channelLiteral);
                channelService = (ChannelService) context.getBean(clazz);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return channelService;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }


}
